package com.zqxx.examine.management.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zqxx.examine.common.utils.Page;
import com.zqxx.examine.management.persistence.UserMapper;
import com.zqxx.examine.management.security.StandardPasswordEncoderForSha1;
import com.zqxx.examine.model.user.Department;
import com.zqxx.examine.model.user.Group;
import com.zqxx.examine.model.user.Role;
import com.zqxx.examine.model.user.User;
@Service
public class UserService {
	@Autowired
	  public UserMapper userMapper;
	  @Transactional
	  public int addUser(User user, String authority, int groupId, HashMap<String, Role> roleMap)
	  {
	    try
	    {
	      //int userId = -1;
	      this.userMapper.insertUser(user);
	      int userId = user.getUserId();
	      this.userMapper.grantUserRole(userId, ((Role)roleMap.get(authority)).getRoleId());
	      if ((user.getDepId() != 0) && (user.getDepId() != -1)) {
	        this.userMapper.addUser2Dep(userId, user.getDepId());
	      }
	      if ("ROLE_TEACHER".equals(authority))
	      {
	        Group group = new Group();
	        group.setGroupName("默认分组");
	        group.setDefaultt(true);
	        group.setUserId(userId);
	        this.userMapper.addGroup(group);
	      }
	      if ("ROLE_STUDENT".equals(authority))
	      {
	        List<Group> groupList = this.userMapper.getGroupListByUserId(user.getCreateBy(), null);
	        boolean flag = false;
	        for (Group group : groupList) {
	          if (group.getGroupId() == groupId)
	          {
	            flag = true;
	            break;
	          }
	        }
	        if (groupId != 0) {
	          if (flag) {
	            this.userMapper.addUserGroup(userId, groupId);
	          } else {
	            throw new Exception("不能将学员分配给一个不存在的分组");
	          }
	        }
	      }
	      return userId;
	    }
	    catch (Exception e)
	    {
	      String cause = e.getCause().getMessage();
	      throw new RuntimeException(cause);
	    }
	  }
	  
	  public List<User> getUserListByRoleId(int roleId, Page<User> page)
	  {
	    List<User> userList = this.userMapper.getUserListByRoleId(roleId, page);
	    return userList;
	  }
	  
	  @Transactional
	  public void updateUser(User user, String oldPassword)
	  {
	    try
	    {
	      this.userMapper.updateUser(user, oldPassword);
	      if (user.getDepId() != -1)
	      {
	        this.userMapper.deleteUser2Dep(user.getUserId());
	        this.userMapper.addUser2Dep(user.getUserId(), user.getDepId());
	      }
	    }
	    catch (Exception e)
	    {
	      throw new RuntimeException(e);
	    }
	  }
	  
	  public List<Group> getGroupListByUserId(int userId, Page<Group> page)
	  {
	    return this.userMapper.getGroupListByUserId(userId, page);
	  }
	  
	  public void addGroup(Group group)
	  {
	    this.userMapper.addGroup(group);
	  }
	  
	  public HashMap<String, Role> getRoleMap()
	  {
	    List<Role> roleList = this.userMapper.getRoleList();
	    HashMap<String, Role> map = new HashMap();
	    for (Role r : roleList) {
	      map.put(r.getAuthority(), r);
	    }
	    return map;
	  }
	  
	  public void changeUserStatus(List<Integer> idList, boolean enabled)
	  {
	    this.userMapper.changeUserStatus(idList, enabled);
	  }
	  
	  public void updateGroup(int groupId, String groupName)
	  {
	    this.userMapper.updateGroup(groupId, groupName);
	  }
	  
	  public void deleteGroup(int groupId)
	  {
	    this.userMapper.deleteGroup(groupId);
	  }
	  
	  public void addUserGroup(int userId, int groupId)
	  {
	    this.userMapper.addUserGroup(userId, groupId);
	  }
	  
	  public List<User> getUserListByGroupIdAndParams(int groupId, String authority, String searchStr, Page<User> page)
	  {
	    return this.userMapper.getUserListByGroupIdAndParams(groupId, authority, searchStr, page);
	  }
	  
	  public void addUsers2Group(String[] userNames, int groupId, HashMap<String, Role> roleMap)
	  {
	    List<User> userList = this.userMapper.getUserByNames(userNames, ((Role)roleMap.get("ROLE_STUDENT")).getRoleId());
	    List<Integer> idList = new ArrayList();
	    for (User user : userList) {
	      idList.add(Integer.valueOf(user.getUserId()));
	    }
	    this.userMapper.addUsers2Group(idList, groupId);
	  }
	  
	  public void deleteUserGroup(int userId, int groupId, int managerId)
	  {
	    this.userMapper.deleteUserGroup(userId, groupId, managerId);
	  }
	  
	  public List<Department> getDepList(Page<Department> page)
	  {
	    return this.userMapper.getDepList(page);
	  }
	  
	  public void addDep(Department dep)
	  {
	    this.userMapper.addDep(dep);
	  }
	  
	  public void updateDep(Department dep)
	  {
	    this.userMapper.updateDep(dep);
	  }
	  
	  public void deleteDep(int depId)
	  {
	    this.userMapper.deleteDep(depId);
	  }
	  
	  public void updateUserPwd(String userName, String password, String authority)
	    throws Exception
	  {
	    User user = this.userMapper.getUserByName(userName);
	    if ((user.getRoles().contains(authority)) && (!"ROLE_ADMIN".equals(authority))) {
	      throw new Exception("教师只能更新学员的密码！");
	    }
	    PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
	    password = passwordEncoder.encode(password + "{" + userName + "}");
	    User tmpUser = new User();
	    tmpUser.setUserId(user.getUserId());
	    tmpUser.setPassword(password);
	    this.userMapper.updateUser(tmpUser, null);
	  }
}
